package dao

import (
	"fmt"
	"time"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/models/statistics"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
)

// 获取用户分析列表
func (d *StatisticsDao) FetchNoSettlementPlaceList(param *request.NoSettlementPlaceReq) *dingo.ErrorWrap {

	var (
		lst    []*statistics.StatisticsUserList
		count  int64
		limit  int = param.PageSize
		offset int = param.PageSize * (param.PageNo - 1)
	)

	db := global.Orm.Debug().Table("statistics_place sp").
		Select("SUM(settlement_complete) as total_settlement").
		Joins("LEFT JOIN places p ON sp.place_id = p.id")

	if param.PlaceId > 0 { db.Where("sp.place_id = ?", param.PlaceId) }
	if param.PlaceName != "" { db.Where("p.place_name LIKE ?", fmt.Sprint("%", param.PlaceName, "%")) }
	if param.City != "" { db.Where("p.city or p.province LIKE ?", fmt.Sprint("%", param.City, "%")) }
	if param.ProjectLabel != "" { db.Where("p.project_label = ?", param.ProjectLabel) }

	dnum := 91
	if param.DayNum > 0 { dnum = param.DayNum }
	endDate := time.Now().AddDate(0, 0, -1).Format("2006-01-02")
	startDate := time.Now().AddDate(0, 0, -dnum).Format("2006-01-02")

	db.Where("date_str >= ? and date_str <= ?", startDate, endDate)

	db.Group("place_id")

	//db.Order("su.date_str DESC")

	db.Limit(limit).Offset(offset).Find(&lst).Limit(-1).Offset(-1).Count(&count)

	return dingo.ErrorIf(db.Error, lst, count)
}
